<template>
  <div>
    <Header></Header>
    <div class="m-content">
      <h2>{{blog.title}}</h2>
      <div v-if="ownBlog">
        <el-link icon="el-icon-edit">
          <router-link :to="{name: 'BlogEdit', params: {blogId: blog.id}}">编辑</router-link>
        </el-link>
        <el-divider direction="vertical"></el-divider>
        <el-link icon="el-icon-delete" @click="delClick">删除</el-link>
      </div>

      <el-divider></el-divider>
      <div class="markdown-body" v-html="blog.content"></div>
    </div>
  </div>
</template>

<script>
import Header from "../components/Header";
import "github-markdown-css";
export default {
  name: "BlogDetail",
  components: {
    Header,
  },
  data() {
    return {
      blog: {
        id: "",
        title: "",
        description: "",
        content: "",
      },
      ownBlog: false,
    };
  },
  methods: {
    delClick() {
      this.$confirm("此操作将永久删除该博客, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const blogId = this.$route.params.blogId;
          if (blogId) {
            const _this = this;
            _this.$axios
              .post(
                "blog/del",
                { id: blogId },
                {
                  headers: {
                    Authorization: localStorage.getItem("token"),
                  },
                }
              )
              .then((res) => {
                if (res.status === 200) {
                  _this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  _this.$router.push("/blogs");
                } else {
                  _this.$message({
                    type: "error",
                    message: "删除失败!",
                  });
                }
              });
          }
        })
        .catch((exp) => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });
    },
  },
  created() {
    const blogId = this.$route.params.blogId;
    if (blogId) {
      const _this = this;
      _this.$axios.get("/blog/" + blogId).then((res) => {
        const blog = res.data.data;
        _this.blog.id = blog.id;
        _this.blog.title = blog.title;
        _this.blog.description = blog.description;

        // var MardownIt = require('markdown-it');
        // var md = new MardownIt();
        // var result = md.render(blog.content);

        var md = require("markdown-it")();
        var result = md.render(blog.content);

        _this.blog.content = result;

        _this.ownBlog = blog.userId === _this.$store.getters.getUserInfo.id;
      });
    }
  },
};
</script>

<style scoped>
.m-content {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  min-height: 700px;
  padding: 20px 15px;
}
</style>